package OptimalAlgorithm.PrefixSum;
//给你一个整数数组 nums，返回 数组 answer ，其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。
//eg:
//输入: nums = [1,2,3,4]
//输出: [24,12,8,6]
public class ProductExceptSelf {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] answer  = new int[n];
        int[] f = new int[n];
        f[0] = 1;
        int[] g = new int[n];
        g[n - 1] = 1;
        for (int i = 0; i < n; i++) {
            if(i != 0){
                f[i] = f[i - 1] * nums[i - 1];
            }
        }
        for (int i = n - 2; i >= 0 ; i++) {
                g[i] = g[i + 1] * nums[i + 1];
        }
        for (int i = 0; i < n; i++) {
            answer[i] = f[i] * g[i];
        }
        return answer;
    }
}
